package com.sxf.web;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.web.context.request.WebRequest;

import com.sxf.common.tools.WPConstants;
import com.sxf.domain.viewbean.UserVO;
import com.sxf.util.CookieUtils;
import com.sxf.util.SysLogUtil;

public class WebHelp {

	public static UserVO getSessionUser(HttpServletRequest request,
			HttpServletResponse response, CacheManager cm) throws Exception {
		UserVO user = null;
		Object o = getSessionValue(request, response, cm, CookieUtils.USER_ID,
				WPConstants.SESSION_CACHE);
		if (o != null && o instanceof UserVO) {
			user = (UserVO) o;
		}
		return user;
	}

	public static Object getSessionValue(HttpServletRequest request,
			HttpServletResponse response, CacheManager cm, String cookieId,
			String cacheKey) throws Exception {
		String uuid = CookieUtils.findCookie(request, response, cookieId);
		Object o = null;
		if (StringUtils.isNotBlank(uuid)) {
			try {
				o = cm.getCache(cacheKey).get(uuid, Object.class);
			} catch (Exception e) {
				SysLogUtil.log.error(e.getMessage());
			}
		}
		return o;
	}

	/**
	 * 移除spring 相关的值(format)
	 * 
	 * @param request
	 */
	public static void removeParameter(HttpServletRequest request) {
		Map<String, String[]> map = null;
		try {
			map = request.getParameterMap();
			Method method = map.getClass().getMethod("setLocked",
					new Class[] { boolean.class });
			method.invoke(map, new Object[] { new Boolean(false) });
			// map.remove("format");
			map.put("format", null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean isAjaxRequest(WebRequest webRequest) {
		String requestedWith = webRequest.getHeader("X-Requested-With");
		return requestedWith != null ? "XMLHttpRequest".equals(requestedWith)
				: false;
	}

	public static boolean isAjaxUploadRequest(WebRequest webRequest) {
		return webRequest.getParameter("ajaxUpload") != null;
	}

	public static boolean isAjaxRequest(HttpServletRequest webRequest) {
		String requestedWith = webRequest.getHeader("X-Requested-With");
		return requestedWith != null ? "XMLHttpRequest".equals(requestedWith)
				: false;
	}

	public static boolean isAjaxUploadRequest(HttpServletRequest webRequest) {
		return webRequest.getParameter("ajaxUpload") != null;
	}
}
